﻿using iTool.Cloud.Database.ServiceProvider;
using iTool.Common.Options;

using J2N.Collections.Generic;

using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Placement;
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace iTool.Cloud.Database.MaxVersionPlacementStrategyFixedProvider
{
    public class MaxVersionSynchronizationProvider : IPlacementDirector
    {
        IGrainFactory iGrainFactory;
        public MaxVersionSynchronizationProvider(IGrainFactory iGrainFactory) 
        {
            this.iGrainFactory = iGrainFactory;
        }


        public async Task<SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context)
        {
            Dictionary<SiloAddress, Task<long>> results = new Dictionary<SiloAddress, Task<long>>();

            try
            {
                // ip:port@hash
                //172.24.96.1:20000@401551942
                string table = target.GrainIdentity.PrimaryKeyString; // tableName

                var siloAddresses = context.GetCompatibleSilos(target);

                foreach (var item in siloAddresses)
                {
                    var service = this.iGrainFactory.GetGrain<iTableVersionService>(string.Format("{0}/{1}", item.ToParsableString(), table));
                    results.Add(item, service.GetCurrentVersionAsync());
                }

                await Task.WhenAll(results.Values);

                SiloAddress targetHost = results.First().Key;
                long maxVersion = 0;
                foreach (var item in results)
                {
                    if (item.Value.Result > maxVersion)
                    {
                        maxVersion = item.Value.Result;
                        targetHost = item.Key;
                    }
                }

                return targetHost;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }
    }
}
